
import { compose } from './'
function applyMiddleware(...middlewares){
    return function(createStore){
        return function(reducer,preloadedState){
            let store = createStore(reducer,preloadedState);
            let dispatch //它会指向改造后的dispatch，这时dispatch是undefined
            // middlewareAPI.dispatch 最后指向的就是改造后的dispatch，因为有些时候希望能够嵌套或者说重新派发
            let middlewareAPI = {
                getState:store.getState,
                dispatch:(action)=>dispatch(action)
            }
            let chain = middlewares.map(middleware=>middleware(middlewareAPI)) //把最外边的函数先执行了了，得到next=>action=>{}函数
            dispatch = compose(...chain)(store.dispatch);
            return {
                ...store,
                dispatch
            };
        }
    }
}
export default applyMiddleware;